package com.uum.web.config;

import com.alibaba.fastjson.JSONObject;
import com.uum.common.core.result.Result;
import com.uum.web.exception.BizException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

import java.nio.charset.StandardCharsets;

@Slf4j
public class FeignErrorConfig {
    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }

    /**
     * 自定义错误
     */
    public class UserErrorDecoder implements ErrorDecoder {
        @SneakyThrows
        @Override
        public Exception decode(String methodKey, Response response) {
            // 获取原始的返回内容
            String json = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
            Result result = null;
            // 将返回内容反序列化为Result，这里应根据自身项目作修改
            result = JSONObject.parseObject(json, Result.class);
            if (result != null) {
                return new BizException(result.getMsg());
            }
            // 业务异常抛出简单的 RuntimeException，保留原来错误信息
            return new BizException(json);
        }
    }

}
